package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.utils.DruidJdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @author 高圆圆
 * @date 2023/5/30 17:48
 * 用户数据访问接口实现
 *
 */
public class UserDaoImpl  implements UserDao {
    /**
     * 更新用户的激活状态
     * @param user 用户实体
     */
    @Override
    public void updateUserState(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //sql
        String sql = "update user set state = ? where uid = ?" ;
        int count = qr.update(sql, user.getState(), user.getUid());
    }

    /**
     * 通过用户名查询知指定用户
     * @param username 用户名昵称
     * @return  返回用户实体
     */
    @Override
    public User selectUserByUsername(String username) throws SQLException {
        //第一步
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //第二步
        String sql ="select * from user where username = ?" ;
        //第三部
        User user = qr.query(sql, new BeanHandler<>(User.class), username);
        return user;
    }

    /**
     * 注册用户
     * @param user 用户实体
     */
    @Override
    public void insertUser(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //sql
        String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)" ;
        int count = qr.update(sql,
                user.getUid(),
                user.getUsername(),
                user.getPassword(),
                user.getName(),
                user.getEmail(),
                user.getTelephone(),
                user.getBirthday(),
                user.getSex(),
                user.getState(),
                user.getCode());
    }

    /**
     * 用户的数据访问接口通过激活码找用户
     * @param code 激活码
     * @return 返回用户实体
     */
    @Override
    public User selectUserByCode(String code) throws SQLException {
        //执行对象
        QueryRunner qr = new QueryRunner(DruidJdbcUtils.getDataSource()) ;
        //sql
        String sql = "select * from user where code = ?" ;
        //查询
        User user = qr.query(sql, new BeanHandler<>(User.class), code);
        return user;
    }
}
